import { defineStore } from 'pinia'
import { getContents } from '@/api/book'
import { getBookContentDb } from '@/utils/localDb'
import bookContentContract from '@/contracts/db/bookContentContract'

export const useBookContentStore = defineStore('bookContentStore', () => {
  // 加载书籍内容
  function loadContent(bookId, chapter) {
    const chapterId = chapter.id
    const bookContentDb = getBookContentDb(bookId, chapterId)
    return bookContentDb.getItem(bookContentContract.item.content).then((res) => {
      if (res) {
        return Promise.resolve(res)
      } else {
        return getContents(chapterId).then((apiRes) => {
          bookContentDb.setItem('bookContent', apiRes.data)
          bookContentDb.setItem('chapterName', chapter.name)
          return Promise.resolve(apiRes.data)
        })
      }
    })
  }

  return {
    loadContent,
  }
})
